package service

import (
	"encoding/json"
	"errors"
	"os"
	"sort"
	"your-tool/internal/define"
)

// 获取菜单列表
func GetMenuList() ([]*define.Menu,error) {
	dir, _ := os.Getwd()
	b, err := os.ReadFile(dir + string(os.PathSeparator) + define.MenuFileName)
	if errors.Is(err, os.ErrNotExist) {
		return nil, err
	}

	menuList := new(define.MenuList)
	err = json.Unmarshal(b, &menuList)
	if err != nil {
		return nil, err
	}
	sort.SliceStable(menuList.List, func(i, j int) bool {
		return menuList.List[i].Sort > menuList.List[j].Sort
	})
	return menuList.List, nil
}

// 创建菜单
func CreateMenu(menu *define.Menu) error {

	data := new(define.MenuList)
	dir, _ := os.Getwd()
	b, err := os.ReadFile(dir + string(os.PathSeparator) + define.MenuFileName)
	// 不存在创建
	if errors.Is(err, os.ErrNotExist) {
		data.List = []*define.Menu{menu}
		b, _ = json.Marshal(data)
		// 创建
		os.MkdirAll(dir,os.ModePerm)
		os.WriteFile(dir + string(os.PathSeparator) + define.MenuFileName, b, os.ModePerm)
		return nil
	}
	// 存在读取，再追加
	json.Unmarshal(b, &data)
	data.List = append(data.List, menu)
	b, _ = json.Marshal(data)
	os.WriteFile(dir + string(os.PathSeparator) + define.MenuFileName, b, os.ModePerm)
	return nil
}

// 修改菜单
func UpdateMenu(menu *define.Menu) error {
	data := new(define.MenuList)
	dir, _ := os.Getwd()
	b, err := os.ReadFile(dir + string(os.PathSeparator) + define.MenuFileName)
	// 不存在则报错
	if err != nil {
		return err
	}
	json.Unmarshal(b, &data)
	for i, v := range data.List {
		if v.Id == menu.Id {
			data.List[i] = menu
			break
		}
	}
	b, _ = json.Marshal(data)
	os.WriteFile(dir + string(os.PathSeparator) + define.MenuFileName, b, os.ModePerm)
	return nil
}